import logging
from logging.handlers import TimedRotatingFileHandler
import os
from datetime import datetime

class Logger:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Logger, cls).__new__(cls)
            cls._instance._initialize_logger()
        return cls._instance
    
    def _initialize_logger(self):
        # 创建logger
        self.logger = logging.getLogger('RAG')
        self.logger.setLevel(logging.INFO)
        
        # 创建logs目录
        if not os.path.exists('logs'):
            os.makedirs('logs')
        
        # 创建文件处理器，使用固定的文件名
        log_file = os.path.join('logs', 'rag.log')
        file_handler = TimedRotatingFileHandler(
            filename=log_file,
            when='midnight',      # 每天午夜切换日志文件
            interval=1,           # 每天一个文件
            backupCount=5,        # 保留5天的日志文件
            encoding='utf-8'      # 明确指定 UTF-8 编码
        )
        file_handler.suffix = "%Y-%m-%d"  # 日志文件后缀格式
        file_handler.setLevel(logging.INFO)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # 设置日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # 清除现有的处理器
        if self.logger.handlers:
            self.logger.handlers.clear()
            
        # 添加处理器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
        
        # 设置日志文件权限
        try:
            os.chmod(log_file, 0o666)
        except Exception as e:
            print(f"设置日志文件权限失败: {e}")
    
    @classmethod
    def get_logger(cls):
        if cls._instance is None:
            cls()
        return cls._instance.logger

# 创建全局logger实例
logger = Logger.get_logger() 